import ImageFont, ImageDraw, Image
import sys
import consultasBD

#>>> from barras import imprimir_etiquetas as ie
#>>> a = ie([("*4092*", "zapato", 10, "x", "v"), ("*5010*", "bolso", 55, "m", "r")])
#>>> a.imprimir()

ANCHO_CODIGO = 350 # Relacion 1,37 (ALTO_CODIGO * 11 / ANCHO_CODIGO * 4)
#aLTO_CODIGO  = 350,195 y 12 columnas funcas#
ALTO_CODIGO  = 195#
OFFSET = 0

class imprimir_etiquetas(object):
    def __init__(self, etiquetas, proveedor):
        self.etiquetas = etiquetas
        self.proveedor = proveedor
        print self.etiquetas

    def imprimir(self):
        imagenes_barras = []
        for et in self.etiquetas:
            imagenes_barras.append(self.imagen_barra(et))
            
        imagenes_filas = []
        for j in range(0, len(imagenes_barras), 4):
            barras = imagenes_barras[j:j + 4]
            imagenes_filas.append(self.imagen_fila(barras))	
        
        imagenes_hojas = []
        for j in range(0, len(imagenes_filas), 12):
            filas = imagenes_filas[j:j + 12]
            imagenes_hojas.append(self.imagen_hoja(filas))
                    
        self.imprimir_hojas(imagenes_hojas)
     
        #imagen_final = self.emparejar_barras(img1, img2, file_name="codgenerados/temp%s.png" % num)
        #self.imprimir_barras(file_name="codgenerados/temp%s.png" % num)

    def imagen_fila(self, barras):
        img_result = Image.new(mode="RGBA", size=(ANCHO_CODIGO*len(barras), ALTO_CODIGO), color=(255, 255, 255)) 

        for i, img in enumerate(barras):
            box = list(img.getbbox())
            
            box[0] = box[2] * i
            box[2] *= (i + 1)
            img_result.paste(img, box)
        
        return img_result        
        
    def imagen_hoja(self, filas):
        #img_result = Image.new(mode="RGBA", size=(ANCHO_CODIGO*4, ALTO_CODIGO*len(filas)), color=(255, 255, 255)) 
        img_result = Image.new(mode="RGBA", size=(ANCHO_CODIGO*4, ALTO_CODIGO*12), color=(255, 255, 255)) 

        for i, img in enumerate(filas):
            box = list(img.getbbox())
            
            box[1] = box[3] * i
            box[3] *= (i + 1)
            img_result.paste(img, box)
            
        img_result.show()
        return img_result

        
    def imagen_barra(self, (id_producto_talle_color, codsussan, descri, precio, talle, color)):
        def _image_precio(precio):
            precio = "$%s" % precio
            image_precio = Image.new("RGB", (ALTO_CODIGO, 50), (255,255,255))
            draw = ImageDraw.Draw(image_precio)
            draw.text((50,10), precio, font=fuente_precio, fill=(0,0,0))
            image_precio = image_precio.rotate(90)        
            return image_precio
            
        def _codsussan_barras(codsussan):
            '''Prepara el codsussan para que se pueda codificar en barras'''
            codsussan_barras = list(codsussan)
            #codsussan_barras.reverse()
            codsussan_barras = "*" + "".join(codsussan_barras) + "*"
            codsussan_reversed = list(codsussan)
            #codsussan_reversed.reverse()
            codsussan_reversed = "".join(codsussan_reversed)        
            return codsussan_reversed
            
        def _id_producto_talle_color_barra(id_producto_talle_color):
            '''Prepara el ptc para que se pueda codificar en barras'''
            id_producto_talle_color_barra = str(id_producto_talle_color)
            id_producto_talle_color_barra = list(id_producto_talle_color_barra)
            #id_producto_talle_color_barra.reverse()
            id_producto_talle_color_barra = "*%s*" % "".join(id_producto_talle_color_barra)        
            return id_producto_talle_color_barra
            
        def _nombreColor(color):
            '''Obtiene el texto del color'''
            SQL="SELECT nombre FROM COLORES WHERE idcolor='%s'" % (color)
            resultado = consultasBD.ordenCrudaResultDict(SQL)
            nombreColor = resultado["nombre"]         
            return nombreColor
    
        fuente_barras = ImageFont.truetype("Fonts\FRE3OF9X.TTF", 74)
        fuente_alfa = ImageFont.truetype("Fonts\ARIAL.TTF", 24)
        fuente_precio = ImageFont.truetype("Fonts\ARIBLK.TTF", 20)
    
        codsussan = str(codsussan)
        
        id_producto_talle_color_barra = _id_producto_talle_color_barra(id_producto_talle_color)      
        codsussan_barras = _codsussan_barras(codsussan)
        
        texto_barra = "*%s%s%s*" % (color, talle, codsussan_barras)
        texto_humano_codsussan_proveedor = "%s - %s - %s" % (id_producto_talle_color, codsussan, self.proveedor)
        texto_descri = "%s" % (descri.upper())
        nombreColor = _nombreColor(color)               
        texto_talle_color = "Talle:%s - Color:%s-%s" % (talle,color,nombreColor)
        
        #Se crea la imagen principal con el codigo de barra y todos los datos menos el PRECIO
        largo_barra,ancho_barra = fuente_barras.getsize(texto_barra)
        largo_descri,ancho_descri = fuente_alfa.getsize(texto_descri)        

        image = Image.new("RGB", (ANCHO_CODIGO,ALTO_CODIGO), (255,255,255))
        draw = ImageDraw.Draw(image)
        draw.text((2,2), texto_descri, font=fuente_alfa, fill=(0,0,0))
        #draw.text((ancho_barra / 2,ancho_descri * 3 + ancho_barra), texto_humano_codsussan_proveedor, font=fuente_alfa, fill=(0,0,0))
        draw.text((2,140), texto_humano_codsussan_proveedor, font=fuente_alfa, fill=(0,0,0))
        draw.text((2,70), id_producto_talle_color_barra, font=fuente_barras, fill=(0,0,0))
        #draw.text((2, ancho_descri * 3), id_producto_talle_color_barra, font=fuente_barras, fill=(0,0,0))
        print str(ancho_descri*3)
        
        draw.text((2,30), texto_talle_color, font=fuente_alfa, fill=(0,0,0))
        #draw.text((3,ancho_descri * 2), texto_talle_color, font=fuente_alfa, fill=(0,0,0))
        #Se crea la imagen del precio y se pega a la imagen principal
        image_precio = _image_precio(precio)
        image.paste(image_precio, (265, 0))
        
        return image
        
    def imprimir_hojas(self, hojas):
        for i, hoja in enumerate(hojas):
            file_name = "codgenerados/temp%s.png" % i
            hoja.save(file_name)
            self.win_print(file_name)
            

    def win_print(self, file_name="codgenerados/temp.png"):
        import win32print
        import win32ui
        from PIL import Image, ImageWin

        #
        # Constants for GetDeviceCaps
        #
        #
        # HORZRES / VERTRES = printable area
        #
        HORZRES = 8
        VERTRES = 10
        #
        # LOGPIXELS = dots per inch
        #
        LOGPIXELSX = 88
        LOGPIXELSY = 90
        #
        # PHYSICALWIDTH/HEIGHT = total area
        #
        PHYSICALWIDTH = 110
        PHYSICALHEIGHT = 111
        #
        # PHYSICALOFFSETX/Y = left / top margin
        #
        
        PHYSICALOFFSETX = 112
        #PHYSICALOFFSETX = 0
        PHYSICALOFFSETY = 113
        #PHYSICALOFFSETY = 0

        printer_name = win32print.GetDefaultPrinter ()

        #
        # You can only write a Device-independent bitmap
        #  directly to a Windows device context; therefore
        #  we need (for ease) to use the Python Imaging
        #  Library to manipulate the image.
        #
        # Create a device context from a named printer
        #  and assess the printable size of the paper.
        #
        hDC = win32ui.CreateDC ()
        hDC.CreatePrinterDC (printer_name)
        printable_area = hDC.GetDeviceCaps (HORZRES), hDC.GetDeviceCaps (VERTRES)
        printer_size = hDC.GetDeviceCaps (PHYSICALWIDTH), hDC.GetDeviceCaps (PHYSICALHEIGHT)
        printer_margins = hDC.GetDeviceCaps (PHYSICALOFFSETX), hDC.GetDeviceCaps (PHYSICALOFFSETY)

        #
        # Open the image, rotate it if it's wider than
        #  it is high, and work out how much to multiply
        #  each pixel by to get it as big as possible on
        #  the page without distorting.
        #
        
        bmp = Image.open (file_name)
        
        #if bmp.size[0] > bmp.size[1]:
        #  bmp = bmp.rotate (90)

        ratios = [1.0 * printable_area[0] / bmp.size[0], 1.0 * printable_area[1] / bmp.size[1]]
        scale = min (ratios)

        #
        # Start the print job, and draw the bitmap to
        #  the printer device at the scaled size.
        #
        hDC.StartDoc (file_name)
        hDC.StartPage ()

        dib = ImageWin.Dib (bmp)
        scaled_width, scaled_height = [int (scale * i) for i in bmp.size]
        x1 = int ((printer_size[0] - scaled_width) / 2)
        y1 = int ((printer_size[1] - scaled_height) / 2)
        x2 = x1 + scaled_width
        y2 = y1 + scaled_height
        dib.draw (hDC.GetHandleOutput (), (x1, y1, x2, y2))
        #dib.draw (hDC.GetHandleOutput (), (0, 0, 0, 0))

        hDC.EndPage ()
        hDC.EndDoc ()
        hDC.DeleteDC ()	
